#pragma once
#include "requestor.h"
#include <unordered_map>

namespace rpc
{
    namespace client
    {
        class TopicManager
        {
        public:
            using ptr = std::shared_ptr<TopicManager>;
            using SubCallback = std::function<void(const std::string &, const std::string &)>;
            TopicManager(Requestor::ptr &requestor)
                : _requestor(requestor)
            {
            }
            bool create(const BaseConnection::ptr &conn, const std::string &key)
            {
                return commRequest(conn, key, TopicOptype::TOPIC_CREATE);
            }
            bool remove(const BaseConnection::ptr &conn, const std::string &key)
            {
                return commRequest(conn, key, TopicOptype::TOPIC_REMOVE);
            }
            bool subsribe(const BaseConnection::ptr &conn, const std::string &key, const SubCallback &cb)
            {
                addSubscribe(key, cb);
                bool ret = commRequest(conn, key, TopicOptype::TOPIC_SUBSCRIBE);
                if (ret == false)
                {
                    delSubscribe(key);
                    return false;
                }
                return true;
            }
            bool cancel(const BaseConnection::ptr &conn, const std::string &key)
            {
                delSubscribe(key);
                return commRequest(conn, key, TopicOptype::TOPIC_CANCEL);
            }
            bool publish(const BaseConnection::ptr &conn, const std::string &key, const std::string &msg)
            {
                return commRequest(conn, key, TopicOptype::TOPIC_PUBLISH, msg);
            }
            void onpublish(const BaseConnection::ptr &conn, const TopicRequest::ptr &msg)
            {
                auto type = msg->optype();
                if (type != TopicOptype::TOPIC_PUBLISH)
                {
                    ELOG("收到了错误请求");
                    return;
                }
                std::string string_key = msg->topic();
                std::string string_msg = msg->msg();
                auto callback = getSubsrcibe(string_key);
                if (!callback)
                {
                    ELOG("收到了 %s 主题消息，但是该消息无主题处理回调！", string_key.c_str());
                    return;
                }
                return callback(string_key, string_msg);
            }

        private:
            void addSubscribe(const std::string &key, const SubCallback &cb)
            {
                std::unique_lock<std::mutex> locK(_mutex);
                _topic_callbacks.insert(std::make_pair(key, cb));
            }
            void delSubscribe(const std::string &key)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _topic_callbacks.erase(key);
            }
            const SubCallback getSubsrcibe(const std::string &key)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                auto it = _topic_callbacks.find(key);
                if (it == _topic_callbacks.end())
                {
                    return SubCallback();
                }
                return it->second;
            }
            bool commRequest(const BaseConnection::ptr &conn, const std::string &key, TopicOptype type, const std::string &msg = "")
            {
                auto req_msg = MessageFactory::create<TopicRequest>();
                req_msg->setrId(UUID::uuid());
                if (type == TopicOptype::TOPIC_PUBLISH)
                    req_msg->Setmsg(msg);
                req_msg->setMtype(lxprpc::MType::REQ_TOPIC);
                req_msg->Settopic(key);
                req_msg->Setoptype(type);

                BaseMessage::ptr rsp_msg;
                bool ret = _requestor->send(conn, req_msg, rsp_msg);
                if (ret == false)
                {
                    ELOG("主题操作请求失败！");
                    return false;
                }
                auto topic_rsp_msg = std::dynamic_pointer_cast<TopicResponse>(rsp_msg);
                if (!topic_rsp_msg)
                {
                    ELOG("向下转换类型失败");
                    return false;
                }
                if (topic_rsp_msg->rcode() != RCode::RCODE_OK)
                {
                    ELOG("主题操作请求出错：%s", errReason(topic_rsp_msg->rcode()));
                    return false;
                }
                if (topic_rsp_msg->rcode() != RCode::RCODE_OK)
                {
                    ELOG("主题操作请求出错：%s", errReason(topic_rsp_msg->rcode()));
                    return false;
                }
                return true;
            }

        private:
            std::mutex _mutex;
            std::unordered_map<std::string, SubCallback> _topic_callbacks;
            Requestor::ptr _requestor;
        };
    }
}